// 网络配置文件
import { getCurrentConfig } from './environment.js';

// 获取当前环境配置
const currentConfig = getCurrentConfig();

export const NETWORK_CONFIG = {
  // API基础URL（动态获取）
  API_BASE_URL: currentConfig.apiBaseUrl,
  
  // WebSocket URL（动态获取）
  WS_URL: currentConfig.wsUrl,
  
  // 请求超时时间（毫秒）
  TIMEOUT: currentConfig.timeout,
  
  // 重试次数
  MAX_RETRIES: currentConfig.maxRetries,
  
  // 重试间隔（毫秒）
  RETRY_INTERVAL: currentConfig.retryInterval,
  
  // 调试模式
  DEBUG: currentConfig.debug,
  
  // 请求头配置
  DEFAULT_HEADERS: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
};

// 网络请求封装
export const createRequest = (options = {}) => {
  const {
    url,
    method = 'GET',
    data = {},
    header = {},
    timeout = NETWORK_CONFIG.TIMEOUT,
    retries = NETWORK_CONFIG.MAX_RETRIES
  } = options;

  // 合并请求头
  const finalHeader = {
    ...NETWORK_CONFIG.DEFAULT_HEADERS,
    ...header
  };

  // 添加token
  const token = uni.getStorageSync('accessToken');
  if (token) {
    finalHeader['Authorization'] = `Bearer ${token}`;
  }

  // 构建完整URL
  const fullUrl = url.startsWith('http') ? url : `${NETWORK_CONFIG.API_BASE_URL}${url}`;

  return new Promise((resolve, reject) => {
    let retryCount = 0;

    const makeRequest = () => {
      uni.request({
        url: fullUrl,
        method,
        data,
        header: finalHeader,
        timeout,
        success: (result) => {
          console.log(`请求成功: ${method} ${fullUrl}`, result);
          resolve(result);
        },
        fail: (error) => {
          console.error(`请求失败: ${method} ${fullUrl}`, error);
          
          // 如果是网络错误且还有重试次数，则重试
          if (retryCount < retries && (error.errMsg.includes('fail') || error.errMsg.includes('timeout'))) {
            retryCount++;
            console.log(`第 ${retryCount} 次重试: ${method} ${fullUrl}`);
            setTimeout(makeRequest, NETWORK_CONFIG.RETRY_INTERVAL);
          } else {
            reject(error);
          }
        }
      });
    };

    makeRequest();
  });
};

// 检查网络状态
export const checkNetworkStatus = () => {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        console.log('网络类型:', res.networkType);
        if (res.networkType === 'none') {
          uni.showToast({
            title: '网络连接失败，请检查网络设置',
            icon: 'none',
            duration: 3000
          });
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail: (error) => {
        console.error('网络状态检查失败:', error);
        uni.showToast({
          title: '网络状态检查失败',
          icon: 'none',
          duration: 2000
        });
        resolve(false);
      }
    });
  });
};

// 测试网络连接
export const testNetworkConnection = async () => {
  try {
    const result = await createRequest({
      url: '/version/latest',
      method: 'GET',
      timeout: 5000
    });
    console.log('网络连接测试成功:', result);
    return true;
  } catch (error) {
    console.error('网络连接测试失败:', error);
    return false;
  }
};

// 登录请求封装
export const loginRequest = async (loginData) => {
  try {
    // 先检查网络状态
    const isNetworkAvailable = await checkNetworkStatus();
    if (!isNetworkAvailable) {
      throw new Error('网络连接不可用');
    }

    const result = await createRequest({
      url: '/auth/login',
      method: 'POST',
      data: loginData,
      timeout: 10000
    });

    return result;
  } catch (error) {
    console.error('登录请求失败:', error);
    throw error;
  }
};

// 发送验证码请求封装
export const sendCodeRequest = async (identifier) => {
  try {
    const result = await createRequest({
      url: '/auth/send-code',
      method: 'POST',
      data: { identifier },
      timeout: 8000
    });

    return result;
  } catch (error) {
    console.error('发送验证码失败:', error);
    throw error;
  }
};

// 获取人脸识别动作请求封装
export const getFaceActionRequest = async () => {
  try {
    const result = await createRequest({
      url: '/auth/login/face/action',
      method: 'GET',
      timeout: 5000
    });

    return result;
  } catch (error) {
    console.error('获取人脸识别动作失败:', error);
    throw error;
  }
};
